package cn.ffcs.uec.recordsApproval.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.manager.CustomFilesManager;
import cn.ffcs.uec.recordsApproval.component.RecordsApprovalListBoxExt;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.manager.ActRunTaskManager;
import cn.ffcs.uec.recordsApproval.manager.AtiUserManager;
import cn.ffcs.uec.recordsApproval.model.AtiUser;
import cn.ffcs.uec.recordsApproval.vo.HistoricFlow;
import cn.ffcs.uec.recordsApproval.vo.HistoricTaskVo;
import cn.ffcs.uec.recordsApproval.vo.TaskVo;
import cn.ffcs.uec.staffRecords.manager.AtiSpecificFormManager;
import cn.ffcs.uec.staffRecords.utils.HttpClientUtils;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.StrUtil;

public class ApprovalUtil {

	private static CustomFilesManager customFilesManager = (CustomFilesManager) ApplicationContextUtil
			.getBean("customFilesManager");

	
	// 1:本地环境URL请求头 
	 
	 //public static final String REQUESH_HEAD = "http://localhost:80";
	//2:内蒙生产环境URL请求头
	public static final String REQUESH_HEAD = "http://136.224.123.227:9080";
	//3:内蒙测试环境
	//public static final String REQUESH_HEAD = "http://136.224.24.180:9080";

	/**
	 * 流程开关变量类型
	 */
	public static final String ACTIVITY_SWITCH = "activity_switch";
	/**
	 * 人才推荐功能开关(open/close)
	 */
	public static final String TALENT_SWITCH = "talent_switch";

	/**
	 * 流程启动标志： 在sys_dict表中类型type = activity_switch 获取到的value值 是true：则启用流程 false：
	 * 不启用用流程，数据直接入库
	 */
	public static Boolean getActivityFlag() {
		return customFilesManager.getActivitySwitchBySysDictVo(ACTIVITY_SWITCH);
	}
	/**
	 * 专家人才推荐启动标志： 在sys_dict表中类型type = talent_switch 获取到的value值 是open：则推荐功能可维护信息;close
	 * 直接关闭，针对按钮进行操作
	 */
	public static String getTalentSwitch() {
		return customFilesManager.getSysDictVo(TALENT_SWITCH);
	}

	/**
	 * 启动流程URL
	 */
	public static final String START_PROCESS_REQUEST = "/es-web/oa/oaBaseObject/startOaBase";
	/**
	 * 审批流程URL
	 */
	public static final String APPROVAL_PROCESS_REQUEST = "/es-web/oa/oaBaseObject/approvalOaBase";
	/**
	 * 待办列表URL
	 */
	public static final String APPROVAL_TODO_REQUEST = "/es-web/act/task/actTaskTodo";
	/**
	 * 签收URL
	 */
	public static final String CLAIM_REQUEST = "/es-web/oa/oaBaseObject/claim";
	/**
	 * 历史流程URL
	 */
	public static final String HISTORIC_APPROVAL_REQUEST = "/es-web/oa/oaBaseObject/taskHistoric";
	/**
	 * 当前环节审批候选人URL
	 */
	public static final String CURRENT_ASSIGNEE_REQUEST = "/es-web/oa/oaBaseObject/currentTaskAssignNames";
	/**
	 * 流程流转信息URL
	 */
	public static final String HISTORIC_FLOW_REQUEST = "/es-web/oa/oaBaseObject/historicFlows";


	/* 流程定义KEY */
	public static final String STAFF_ENTRY = "staffEntry";
	/**
	 * 外包人员入职 流程定义 KEY
	 */
	public static final String OUT_STAFF_ENTRY = "outStaffEntry";
	/**
	 * 外包人员转正 流程定义 KEY
	 */
	public static final String OUT_STAFF_TRIAL = "outStaffTrial";
	/**
	 * 外包人员调岗 流程定义 KEY
	 */
	public static final String OUT_STAFF_ADJUST_EDIT = "outStaffPsnjobEdit";
	/**
	 * 外包人员信息修改 流程定义 KEY
	 */
	public static final String OUT_STAFF_EDIT = "outStaffEdit";
	/**
	 * 外包人员惩罚 流程定义 KEY
	 */
	public static final String OUT_STAFF_PUNISH_EDIT = "outStaffPunishEdit";
	/**
	 * 外包人员奖励 流程定义 KEY
	 */
	public static final String OUT_STAFF_ENC_EDIT = "outStaffEncEdit";
	/**
	 * 外包人员考核 流程定义 KEY
	 */
	public static final String OUT_STAFF_ASS_EDIT = "outStaffAssess";
	/**
	 * 外包人员专业人才队伍 流程定义 KEY
	 */
	public static final String OUT_STAFF_TALENT_TEAM_EDIT = "outStaffTalentTeamEdit";
	/**
	 * 外包人员任职 流程定义 KEY
	 */
	public static final String OUT_STAFF_PSNJOB_EDIT = "outStaffPsnjobEdit";
	/**
	 * 外包人员离退 流程定义 KEY
	 */
	public static final String OUT_STAFF_RETIRE = "outStaffRetire";
	/**
	 * 外包人员定调资 流程定义KEY
	 */
	public static final String OUT_STAFF_ADJUST_POST = "outStaffAdjustPost";
	/**
	 * 外包人员教育经历新增 流程定义KEY
	 */
	public static final String OUT_STAFF_EDU_ADD = "outStaffEduAdd";
	/**
	 * 外包人员教育经历修改 流程定义KEY
	 */
	public static final String OUT_STAFF_EDU_EDIT = "outStaffEduEdit";
	/**
	 * 专业技术职务新增
	 */
	public static final String OUT_STAFF_TITLE_ADD = "outStaffTitleAdd";
	/**
	 * 专业技术职务修改
	 */
	public static final String OUT_STAFF_TITLE_EDIT = "outStaffTitleEdit";
	/**
	 * 政治面貌新增
	 */
	public static final String OUT_STAFF_PARTYLOG_ADD = "outStaffPartylogAdd";
	/**
	 * 政治面貌修改
	 */
	public static final String OUT_STAFF_PARTYLOG_EDIT = "outStaffPartylogEdit";
	/**
	 * 工作日期修改
	 */
	public static final String OUT_STAFF_WORKDATE_EDIT = "outStaffWorkDateEdit";
	/**
	 * 合同制定调资
	 */
	public static final String STAFF_ADJUST_POST = "staffAdjustPost";

	private static ActRunTaskManager actRunTaskManager = (ActRunTaskManager) ApplicationContextUtil
			.getBean("actRunTaskManager");

	private static AtiSpecificFormManager atiSpecificFormManager = (AtiSpecificFormManager) ApplicationContextUtil
			.getBean("atiSpecificFormManager");

	/**
	 * 启动流程
	 * 
	 * @param formTheme
	 * @param formContent
	 * @param primaryId
	 * @param procDefKey
	 * @param procDefId
	 * @param urgent
	 * @param categoryId
	 */
	public static String startApproval(String startFlowJson) throws Exception {

		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

		String startProcessUrl = REQUESH_HEAD + START_PROCESS_REQUEST;
		params.add(new BasicNameValuePair("startFlowJson", startFlowJson));
		JSONObject jsonObj = HttpClientUtils.postHttp(startProcessUrl, params);
		String procInstId = null;
		if (null != jsonObj) {
			procInstId = (String) jsonObj.get("data");
		}
		return procInstId;

	}

	/**
	 * 签收任务
	 * 
	 * @param taskId
	 * @param assignName
	 */
	public static boolean claim(String taskId) {
		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前登录用户不存在!", "错误提示");
			return false;
		}
		String currentName = PlatformUtil.getCurrentUser().getScreenName();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("taskId", taskId));
		params.add(new BasicNameValuePair("assignName", currentName));
		String claimProcessUrl = REQUESH_HEAD + CLAIM_REQUEST;
		try {
			JSONObject claimObject = HttpClientUtils.postHttp(claimProcessUrl,
					params);
			if (null != claimObject) {
				if (ApprovalConstants.STATUS_OK == (Integer) claimObject
						.get("state")) {
					return true;
				} else {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	/**
	 * 审批流程
	 * 
	 * @param comment
	 *            审批意见
	 * @param flag
	 *            0 or 1
	 * @param taskId
	 * @param procInstId
	 */
	public static boolean approvalPostHttp(String comment, String flag,
			String taskId, String procInstId) {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("comment", comment));
		params.add(new BasicNameValuePair("flag", flag));
		params.add(new BasicNameValuePair("taskId", taskId));
		params.add(new BasicNameValuePair("procInstId", procInstId));
		String approvalProcesssUrl = REQUESH_HEAD + APPROVAL_PROCESS_REQUEST;
		try {
			JSONObject completeObject = HttpClientUtils.postHttp(
					approvalProcesssUrl, params);
			if (null != completeObject) {
				if (ApprovalConstants.STATUS_OK == completeObject.get("state")) {
					return true;
				} else {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	/**
	 * 待办列表
	 * 
	 * @return
	 */
	public static List<TaskVo> approvalTodo() {
		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前用户不存在！", "错误提示");
			return null;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		// 任务审批人设置为当前登录用户
		String currentName = PlatformUtil.getCurrentUser().getScreenName();

		params.put("assignName", currentName);
		String taskTodoUrl = REQUESH_HEAD + APPROVAL_TODO_REQUEST;
		JSONObject jsonObj = null;
		try {
			jsonObj = HttpClientUtils.getHttp(taskTodoUrl, params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null == jsonObj) {
			return null;
		}
		JSONArray data = (JSONArray) jsonObj.get("data");
		if (null == data) {
			return null;
		}
		List<TaskVo> tasks = JSON.parseArray(data.toString(), TaskVo.class);
		return tasks;
	}

	/**
	 * 历史审批记录
	 * 
	 * @return
	 */
	public static List<HistoricTaskVo> historicApproval(String categoryId,
			String startTime, String endTime) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前用户不存在！", "错误提示");
			return null;
		}
		// 任务查询人设置为当前登录用户
		String currentName = PlatformUtil.getCurrentUser().getScreenName();
		params.put("assignName", currentName);
		params.put("categoryId", categoryId);
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		// params.put("assignName", "wangyiren");
		String historicTasksUrl = REQUESH_HEAD + HISTORIC_APPROVAL_REQUEST;

		JSONObject jsonObj = null;
		try {
			jsonObj = HttpClientUtils.getHttp(historicTasksUrl, params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null != jsonObj) {
			Object array = jsonObj.get("data");
			if (null != array) {
				List<HistoricTaskVo> historicTaskVos = JSON.parseArray(
						array.toString(), HistoricTaskVo.class);
				return historicTaskVos;
			}
		}
		return null;
	}

	/**
	 * 单个流程的历史流转环节信息
	 * 
	 * @param procInstId
	 * @return
	 */
	public static List<HistoricFlow> historicFlow(String procInstId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("procInstId", procInstId);
		String historicFlowUrl = REQUESH_HEAD + HISTORIC_FLOW_REQUEST;
		JSONObject jsObject = null;
		try {
			jsObject = HttpClientUtils.getHttp(historicFlowUrl, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null != jsObject) {
			Object data = jsObject.get("data");
			if (null != data) {
				List<HistoricFlow> historicFlows = JSON.parseArray(jsObject
						.get("data").toString(), HistoricFlow.class);
				return historicFlows;
			}
		}
		return null;

	}

	/**
	 * 当前环节任务与候选人
	 * 
	 * @param procInstId
	 * @return
	 */
	public static Map<String, Object> getCurrentAssignNames(String procInstId) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("procInstId", procInstId);
		String currentTaskAssignNameUrl = REQUESH_HEAD
				+ CURRENT_ASSIGNEE_REQUEST;
		JSONObject jsonObject = HttpClientUtils.getHttp(
				currentTaskAssignNameUrl, params);
		JSONObject jsonData = jsonObject.getJSONObject("data");
		if (null != jsonData) {
			JSONObject taskJson = jsonObject.getJSONObject("data")
					.getJSONObject("task");
			TaskVo taskVo = JSON.parseObject(taskJson.toJSONString(),
					TaskVo.class);
			map.put("task", taskVo);
			JSONArray namesJson = jsonObject.getJSONObject("data")
					.getJSONArray("names");
			List<String> names = JSON.parseArray(namesJson.toString(),
					String.class);

			map.put("names", names);
		}
		return map;
	}

	/**
	 * 第一审批人是否是发起人，如果是则直接审批
	 * 
	 * @param procInstId
	 */
	@SuppressWarnings("unchecked")
	public static void isCurrentAssignNames(String procInstId) {
		Map<String, Object> map = getCurrentAssignNames(procInstId);
		TaskVo taskVo = (TaskVo) map.get("task");
		List<String> names = (List<String>) map.get("names");
		if (null != names) {
			for (String name : names) {
				if (name.equals(PlatformUtil.getCurrentUser().getScreenName())) {
					// 签收任务
					boolean isAssign = ApprovalUtil.claim(taskVo.getTaskId());
					if (!isAssign) {
						ZkUtil.showError("任务不存在或已处理完毕！", "错误提示");
						return;
					}
					// 完成任务
					boolean isComplete = ApprovalUtil.approvalPostHttp("",
							ApprovalConstants.ON_APPROVAL_RESULT,
							taskVo.getTaskId(), taskVo.getProcInsId());
					if (!isComplete) {
						ZkUtil.showError("任务不存在或已处理完毕！", "错误提示");
						return;
					}
					break;
				}
			}
		}
	}

	/**
	 * 在审状态不允许再次发起此流程
	 * 
	 * @param procDefId
	 *            流程定义ID
	 */
	public static boolean isOnApproval(String procDefId, Long uecOutStaffId) {
		// 为保持统一，新增数据 不判断在审
		List<Map<String, Object>> runTasks = actRunTaskManager
				.getRuTasksByProcDefId(procDefId);
		if (null != runTasks) {
			String procDefKey = procDefId.split(":")[0];
			for (Map<String, Object> map : runTasks) {
				String procInstId = (String) map.get("PROC_INST_ID_");
				AtiOaBaseObject oaBaseObject = atiSpecificFormManager
						.getAtiOaBaseObjectByProcInstId(procInstId);
				// 入职在审：
				// uec_out_staff_info中有此人一条1320状态记录，uec_trial中有此人一条1320状态记录
				if (OUT_STAFF_ENTRY.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String outStaffIdHis = oaBaseObject.getOutStaffIdHis();
						if (!StrUtil.isNullOrEmpty(outStaffIdHis)
								&& outStaffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil
										.isNullOrEmpty(oaBaseObject.getTrialId())) {
							return true;
						}
					}
				}
				// 转正在审：uec_trial 中有此人一条1320状态记录
				if (OUT_STAFF_TRIAL.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String trialId = oaBaseObject.getTrialId();
						if (!StrUtil.isNullOrEmpty(oaBaseObject.getOutStaffIdHis())
								&& oaBaseObject.getOutStaffIdHis().equals(
										uecOutStaffId.toString())
								&& !StrUtil.isNullOrEmpty(trialId)) {
							return true;
						}
					}
				}
				// 调配在审：uec_out_staff_info中有此人一条1320状态记录，uec_psnjob中有此人一条1320状态记录
				if (OUT_STAFF_ADJUST_EDIT.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String outStaffIdHis = oaBaseObject.getOutStaffIdHis();
						if (!StrUtil.isNullOrEmpty(outStaffIdHis)
								&& outStaffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil.isNullOrEmpty(oaBaseObject
										.getPsnjobIdModify())
								&& !StrUtil.isNullOrEmpty(oaBaseObject
										.getPsnjobIdAdd())) {
							return true;
						}
					}
				}
				// 离退在审：uec_psnjob 中有此人一条1320状态记录
				if (OUT_STAFF_RETIRE.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String outSatffIdHis = oaBaseObject.getOutStaffIdHis();
						if (!StrUtil.isNullOrEmpty(outSatffIdHis)
								&& outSatffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil.isNullOrEmpty(oaBaseObject
										.getPsnjobIdHis())) {
							return true;
						}
					}
				}
				// 合同制定调资在审:uec_psndoc_wadoc 中有此人一条1320状态记录
				if (STAFF_ADJUST_POST.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String satffIdHis = oaBaseObject.getStaffIdHis();
						if (!StrUtil.isNullOrEmpty(satffIdHis)
								&& satffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil.isNullOrEmpty(oaBaseObject
										.getWadocIdModify())) {
							return true;
						}
					}
				}
				// 外包定调资在审:uec_psndoc_wadoc 中有此人一条1320状态记录
				if (OUT_STAFF_ADJUST_POST.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String outSatffIdHis = oaBaseObject.getOutStaffIdHis();
						if (!StrUtil.isNullOrEmpty(outSatffIdHis)
								&& outSatffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil.isNullOrEmpty(oaBaseObject
										.getWadocIdAdd())
								&& !StrUtil.isNullOrEmpty(oaBaseObject
										.getWadocIdModify())) {
							return true;
						}
					}
				}
				// 教育经历在审
				if (OUT_STAFF_EDU_EDIT.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String outSatffIdHis = oaBaseObject.getOutStaffIdHis();
						if (!StrUtil.isNullOrEmpty(outSatffIdHis)
								&& outSatffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil.isNullOrEmpty(oaBaseObject.getEduId())) {
							return true;
						}
					}
				}
				// 专业技术职务在审
				if (OUT_STAFF_TITLE_EDIT.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String outSatffIdHis = oaBaseObject.getOutStaffIdHis();
						if (!StrUtil.isNullOrEmpty(outSatffIdHis)
								&& outSatffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil
										.isNullOrEmpty(oaBaseObject.getTitleId())) {
							return true;
						}
					}
				}
				// 政治面貌在审
				if (OUT_STAFF_PARTYLOG_EDIT.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						String outSatffIdHis = oaBaseObject.getOutStaffIdHis();
						if (!StrUtil.isNullOrEmpty(outSatffIdHis)
								&& outSatffIdHis.equals(uecOutStaffId.toString())
								&& !StrUtil.isNullOrEmpty(oaBaseObject
										.getPartyLogId())) {
							return true;
						}
					}
				}
				// 修改工作日期在审
				if (OUT_STAFF_WORKDATE_EDIT.equals(procDefKey)) {
					if(oaBaseObject !=null) {
						if (!StrUtil.isNullOrEmpty(oaBaseObject.getOutStaffIdHis())
								&& oaBaseObject.getOutStaffIdHis().equals(
										uecOutStaffId.toString())
						// && !StrUtil.isNullOrEmpty(oaBaseObject.getTitleId())
						) {
							return true;
						}
					}
				}
			}
		}
		return false;
	}

	/**
	 * 流程审批结束后显示下一审批人
	 * 
	 * @param procInstId
	 * @param formTheme
	 */
	public static void showNextAssignee(String procInstId, String formTheme) {
		// 获取流程当前环节 的审批人
		String no = "";
		List<Map<String, Object>> list = actRunTaskManager
				.getRuTasks(procInstId);
		if (null == list) {
			ZkUtil.showError("未知错误!", "错误信息");
			return;
		}
		// 流程未结束,查看当前审批人
		if (list.size() > 0) {
			Map<String, Object> map = ApprovalUtil
					.getCurrentAssignNames(procInstId);
			@SuppressWarnings("unchecked")
			List<String> names = (List<String>) map.get("names");
			no = names.get(0);
			AtiUser atiUser = new AtiUser();
			AtiUserManager atiUserManager = (AtiUserManager) ApplicationContextUtil
					.getBean("atiUserManager");
			atiUser.setNo(no);
			atiUser = atiUserManager.findAtiUserByAtiUser(atiUser);
			ZkUtil.showInformation(
					formTheme + "已发起！下一审批人：" + atiUser.getName(), "温馨提示");
		}
		// 流程结束
		if (list.size() == 0) {
			// 流程结束后修改数据状态
			AtiOaBaseObject oaBaseObject = atiSpecificFormManager
					.getAtiOaBaseObjectByProcInstId(procInstId);
			String procDefKey = oaBaseObject.getProcDefId().toString()
					.split(":")[0];
			TaskVo taskVo = new TaskVo();
			taskVo.setProcDefKey(procDefKey);
			RecordsApprovalListBoxExt.setDataStatus(oaBaseObject, taskVo);
			ZkUtil.showInformation(formTheme + "已结束！请查看数据", "温馨提示");
		}
	}

	/**
	 * 获取登录用户
	 * 
	 * @return
	 */
	public static String getCurrentName() {
		String currentName = null;
		if (!StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			currentName = PlatformUtil.getCurrentUser().getScreenName();
		}
		return currentName;
	}

	/**
	 * 判断当前任务是否已被处理
	 * 
	 * @param oaBaseObject
	 */
	public static boolean isTaskCompleted(AtiOaBaseObject oaBaseObject,
			String taskId) {
		List<Map<String, Object>> runTaskList = actRunTaskManager
				.getRuTasks(oaBaseObject.getProcInstId());
		if (runTaskList != null && runTaskList.size() > 0) {
			Map<String, Object> map = getCurrentAssignNames(oaBaseObject
					.getProcInstId());
			TaskVo task = (TaskVo) map.get("task");
			if (taskId.equals(task.getTaskId())) {
				return false;
			} else {
				return true;
			}
		} else {
			// 流程已结束
			return true;
		}
	}
}
